require 'net/https'

module UnfuddleMyEmail
  class Poster
    # Return a new Net::HTTP session for the given +domain+. Optionally,
    # enable +ssl+.
    def self.http(domain, ssl = false)
      http = Net::HTTP.new(domain, ssl ? 443 : 80)
      if ssl
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      return http
    end

    # Post XML content with basic authentication.
    #
    # Arguments:
    # * +domain+: The domain name to use
    # * +uri+: The url minuse the domain
    # * +ssl+: Set true to enable SSL.
    # * +username+: The username to use for Basic Auth.
    # * +password+: The password to use for Basic Auth.
    # * +content+: The content to POST via HTTP.
    #
    # Example:
    #
    #   Poster::post('example.com','/tickets',false,'john','doe','<data>value</data>')
    #
    # Raises error on anything but success or redirect.
    def self.post(domain, uri, ssl, username, password, content)
      request = Net::HTTP::Post.new(uri, {'Content-type' => 'application/xml'})
      request.basic_auth username, password
      request.body = content
      response = http(domain, ssl).request(request)
      case response
      when Net::HTTPSuccess, Net::HTTPRedirection
        return true
      else
        response.error!
      end
    end
  end
end
